// src/main/java/com/example/userdemo/util/ExcelUtil.java
package net.lab1024.sa.admin.common;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class ExcelUtil {

    public static <T> List<T> importExcel(MultipartFile file, Class<T> clazz) {
        List<T> list = new ArrayList<>();
        try (InputStream inputStream = file.getInputStream();
             Workbook workbook = new XSSFWorkbook(inputStream)) {
            
            Sheet sheet = workbook.getSheetAt(0);
            Row headerRow = sheet.getRow(0);
            
            // 获取标题行，用于映射实体类字段
            List<String> headers = new ArrayList<>();
            for (Cell cell : headerRow) {
                headers.add(cell.getStringCellValue());
            }
            
            // 遍历数据行
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;
                
                T obj = clazz.newInstance();
                for (int j = 0; j < headers.size(); j++) {
                    Cell cell = row.getCell(j);
                    if (cell == null) continue;
                    
                    String fieldName = headers.get(j);
                    Field field = clazz.getDeclaredField(fieldName);
                    field.setAccessible(true);
                    
                    // 根据字段类型设置值
                    if (field.getType() == String.class) {
                        cell.setCellType(CellType.STRING);
                        field.set(obj, cell.getStringCellValue());
                    } else if (field.getType() == Integer.class || field.getType() == int.class) {
                        cell.setCellType(CellType.NUMERIC);
                        field.set(obj, (int) cell.getNumericCellValue());
                    }
                    // 其他类型可以继续扩展
                }
                list.add(obj);
            }
        } catch (Exception e) {
            throw new RuntimeException("Excel导入失败: " + e.getMessage());
        }
        return list;
    }

    public static <T> void exportExcel(HttpServletResponse response, List<T> list, 
                                     String fileName, String sheetName, Class<T> clazz) {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet(sheetName);
            
            // 创建标题行
            Field[] fields = clazz.getDeclaredFields();
            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < fields.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(fields[i].getName());
            }
            
            // 填充数据
            for (int i = 0; i < list.size(); i++) {
                Row row = sheet.createRow(i + 1);
                T obj = list.get(i);
                for (int j = 0; j < fields.length; j++) {
                    fields[j].setAccessible(true);
                    Object value = fields[j].get(obj);
                    Cell cell = row.createCell(j);
                    if (value != null) {
                        cell.setCellValue(value.toString());
                    }
                }
            }
            
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
            
            // 写入响应流
            try (OutputStream outputStream = response.getOutputStream()) {
                workbook.write(outputStream);
            }
        } catch (Exception e) {
            throw new RuntimeException("Excel导出失败: " + e.getMessage());
        }
    }
}